#include <windows.h>

#include "qmenudata.h"
#include "qlist.h"

struct QMenuDataPrivate {
	QString menuname;
	QList<QMenuDataPrivate> items;
};

QMenuData::QMenuData()
{
	d = new QMenuDataPrivate;
	d->items.setAutoDelete(TRUE);
}

QMenuData::~QMenuData()
{
	delete d;
}

QMenuData::insertItem(const QString& name)
{
	QMenuDataPrivate *i = new QMenuDataPrivate;
	i->menuname = name;
	d->items.append(i);
}

QMenuData::insertItem(const QString& name, QPopupMenu *popup)
{

	d->items.append(popup->d);
}

static HMENU createPopupMenu(QMenuDataPrivate *d, const QString& name)
{
	static int wIDcounter = 0;

	HMENU popup = CreatePopupMenu();

	MENUITEMINFO i;
	i.cbSize = sizeof(i);
	i.fMask = MIIM_DATA|MIIM_ID|MIIM_STATE|MIIM_SUBMENU|MIIM_TYPE;
	i.fType = MFT_STRING;
	i.fState = MFS_ENABLED;
	i.wID = ++wIDcounter;
	HMENU submenu = NULL;
	if (d->popup)
		HMENU submenu = createPopupMenu(d->popup, d->name);
	i.hSubMenu = submenu;
	i.hbmpChecked = NULL;
	i.hbmpUnchecked = NULL;
	i.dwItemData = 0;
	i.dwTypeData = name;
	i.cch = strlen(i.dwTypeData);

	for (QMenuDataPrivate::Item *i = items.first(); i != 0; i = items.next()) {
		HMENU popup = CreatePopupMenu();
		MENUITEMINFO i;
		i.cbSize = sizeof(i);
		i.fMask = MIIM_DATA|MIIM_ID|MIIM_STATE|MIIM_SUBMENU|MIIM_TYPE;
		i.fType = MFT_STRING;
		i.fState = MFS_ENABLED;
		i.wID = 0;
		i.hSubMenu = popup;
		i.hbmpChecked = NULL;
		i.hbmpUnchecked = NULL;
		i.dwItemData = 0;
		i.dwTypeData = i->name;
		i.cch = strlen(i.dwTypeData);

		InsertMenuItem(menu, 0, TRUE, &i);
	}

	return HMENU;
}

void QMenuData::buildMenu(WId id)
{
	HMENU menu = CreateMenu();

	for (QMenuDataPrivate::Item *i = items.first(); i != 0; i = items.next()) {
		HMENU popup = CreatePopupMenu();
		MENUITEMINFO i;
		i.cbSize = sizeof(i);
		i.fMask = MIIM_DATA|MIIM_ID|MIIM_STATE|MIIM_SUBMENU|MIIM_TYPE;
		i.fType = MFT_STRING;
		i.fState = MFS_ENABLED;
		i.wID = 0;
		i.hSubMenu = popup;
		i.hbmpChecked = NULL;
		i.hbmpUnchecked = NULL;
		i.dwItemData = 0;
		i.dwTypeData = i->name;
		i.cch = strlen(i.dwTypeData);

		InsertMenuItem(menu, 0, TRUE, &i);
	}

	i.wID = 1;
	i.hSubMenu = NULL;
	i.dwTypeData = "Quit";
	i.cch = strlen(i.dwTypeData);
	InsertMenuItem(popup, 0, TRUE, &i);
	SetMenu(id, menu);
}
